package tests.read;

import static org.junit.Assert.fail;

import java.util.ArrayList;

import model.Budget;
import model.BudgetFactory;
import model.Line;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import cc.test.bridge.BridgeInterface;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

/*
 * 
 * Attempts to fetch the second line of a budget with 2 lines
 * 
 */

public class LineQueryTest01
{
	Budget budget;
	BudgetFactory factory;
	Line line;

	@Before
	public void setUp() throws Exception
	{
		factory = new BudgetFactory();
		budget = (Budget) factory.create();
        budget.setName("Test budget");
        budget.setDescription("This is a test budget.");
        
        line = (Line) budget.createLine();
        line.setName("Line");
		budget.add(line);
		budget.commit();
	}

	@After
	public void tearDown() throws Exception
	{
		Helper.delete( line, "Lines", WorkletContext.getInstance());
		Helper.delete( budget, "Budgets", WorkletContext.getInstance());
	}

	@Test
	public void test()
	{
		try
		{
			BasicDBObject criteria = new BasicDBObject("entry.name", line.getName());
			String predicate = JSON.serialize(criteria);
			
			@SuppressWarnings("unchecked")
			ArrayList<BridgeInterface> results = Helper.query("Lines", predicate, WorkletContext.getInstance());
			if(results.size() == 0 )
			{
				fail("Line name query failed");
			}
		}
		catch(Exception e)
		{
			fail("Line name query failed with exception " + e);
			System.out.println("----------------");
			e.printStackTrace();
		}
	}
}